package com.ego.product.controller;

import java.util.Arrays;
import java.util.concurrent.ExecutionException;

import com.ego.common.constant.SystemConstant;
import com.ego.common.vo.PageVo;
import com.ego.product.vo.SpuInfoSearchVo;
import com.ego.product.vo.spu.SpuInfoVo;
import com.ego.product.vo.spu.SpuSaveVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.ego.product.po.SpuInfo;
import com.ego.product.service.SpuInfoService;
import com.ego.common.util.Result;

import javax.validation.Valid;

/**
 * @program: ego
 * @description spu信息控制器
 * @author KamTang
 * @date 2022-11-13 12:56:14
 */
@RestController
@RequestMapping("product/spu-info")
public class SpuInfoController {

    @Autowired
    private SpuInfoService spuInfoService;

    /**
     * 商品出售（上架）
     */
    @PostMapping("/{spuId}/sale")
    public Result sale(@Valid @PathVariable("spuId") Long spuId) {
        spuInfoService.sale(spuId);
        return Result.ok();
    }

    /**
     * 搜索
     */
    @PostMapping("/search")
    public Result search(@Valid @RequestBody SpuInfoSearchVo search) {
        PageVo<SpuInfo> page = spuInfoService.search(search);
        return Result.ok().put("page", page);
    }

    /**
     * 信息
     */
    @GetMapping("/get/{id}")
    public Result get(@PathVariable("id") Long id){
		SpuInfo spuInfo = spuInfoService.getById(id);
        return Result.ok().put("spuInfo", spuInfo);
    }

    @GetMapping("/getBySkuId/{skuId}")
    public Result getBySkuId(@PathVariable("skuId") Long skuId) {
        SpuInfo spuInfo = spuInfoService.get(skuId);
        SpuInfoVo spuInfoVo = spuInfo.toVo();
        return Result.ok().put("spuInfoVo", spuInfoVo);
    }

    /**
     * 发布商品
     */
    @PostMapping("/save")
    public Result save(@Valid @RequestBody SpuSaveVo vo) throws ExecutionException, InterruptedException {
		try {
            spuInfoService.saveSpu(vo);
        } catch (Exception e) {
            return Result.error(SystemConstant.Status.UNKNOWN_EXCEPTION.getCode(), SystemConstant.Status.UNKNOWN_EXCEPTION.getMsg());
        }
        return Result.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    public Result update(@RequestBody SpuInfo spuInfo){
		spuInfoService.updateById(spuInfo);
        return Result.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody Long[] ids){
		spuInfoService.removeByIds(Arrays.asList(ids));
        return Result.ok();
    }

}
